package com.juzi.wopu.web;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.juzi.wopu.domain.SysCode;
import com.juzi.wopu.query.PageList;
import com.juzi.wopu.query.SysCodeQuery;
import com.juzi.wopu.service.ISysCodeService;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

public class SysCodeAction extends CRUDAaction<SysCode> {

	private static final long serialVersionUID = 1L;

	private ISysCodeService sysCodeService;

	private SysCode sysCode = new SysCode();
	
	private SysCodeQuery baseQuery = new SysCodeQuery();
	
	private PageList pageList;
	
	public void setSysCodeService(ISysCodeService sysCodeService) {
		this.sysCodeService = sysCodeService;
	}
	
	@Override
	protected void list() {
		this.pageList = sysCodeService.findByQuery(baseQuery);
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	public void validateSave() {
		if (StringUtils.isBlank(sysCode.getsName())) {
			addFieldError("name", "名称不能为空");
		}
	}

	@Override
    @InputConfig(methodName="input")
	public String save() throws Exception {
		if(id==null){
			baseQuery.setCurrentPage(Integer.MAX_VALUE);
			sysCode.setiSort(1L);
		}
		sysCodeService.save(sysCode);
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			if (id != null) {
				sysCodeService.delete(id);
				out.print("{\"success\":true,\"msg\":\"删除成功\"}");
			}else{
				out.print("{\"success\":false,\"msg\":\"没有删除成功\"}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"success\":false,\"msg\":\"异常信息:"+e.getMessage()+"\"}");
		}
		return null;
	}

	@Override
	public void prepareInput() throws Exception {
		if (id != null) {
			sysCode = sysCodeService.get(id);
		}
	}

	@Override
	public void prepareSave() throws Exception {
		if (id == null) {
			sysCode = new SysCode();
		} else {
			sysCode = sysCodeService.get(id);
		}
	}

	@Override
	public SysCode getModel() {
		return sysCode;
	}

	public PageList getPageList() {
		return pageList;
	}

	public SysCodeQuery getBaseQuery() {
		return baseQuery;
	}

	public void setBaseQuery(SysCodeQuery baseQuery) {
		this.baseQuery = baseQuery;
	}
}
